package com.imti.retrofitweatherdemo;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.bottomnavigation.BottomNavigationView.OnNavigationItemSelectedListener;
import com.imti.retrofitweatherdemo.fragment.CinemaFragment;
import com.imti.retrofitweatherdemo.fragment.HomeFragment;
import com.imti.retrofitweatherdemo.fragment.MineFragment;
import com.imti.retrofitweatherdemo.fragment.VideoFragment;
import com.imti.retrofitweatherdemo.logic.IWeatherLogic;
import com.imti.retrofitweatherdemo.logic.WeatherLogic;
import com.imti.retrofitweatherdemo.logic.WeatherResult.CityWeather;
import com.sunsky.marqueeview.MarqueeView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements IWeatherLogic
{

    private static final String TAG = MainActivity.class.getSimpleName();

    private WeatherLogic weatherLogic;

    private BottomNavigationView mHomeBottom;

    private List<Fragment> mHomeFragments = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        weatherLogic = WeatherLogic.getInstance((BaseApplication) getApplication());
        weatherLogic.setWeatherLogic(this);

        initData();

        initView();

    }

    private void initView()
    {
        mHomeBottom = findViewById(R.id.news_home_bottom);

        mHomeFragments.add(new HomeFragment());
        mHomeFragments.add(new VideoFragment());
        mHomeFragments.add(new CinemaFragment());
        mHomeFragments.add(new MineFragment());

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < mHomeFragments.size(); i++)
        {
            ft.add(R.id.home_container, mHomeFragments.get(i));

            if (i != 0)
            {
                ft.hide(mHomeFragments.get(i));
            }
        }

        ft.commit();

        mHomeBottom.setOnNavigationItemSelectedListener(new OnNavigationItemSelectedListener()
        {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item)
            {
                replaceHomeFragment(item.getItemId());
                return true;
            }
        });

        initTitleRollText();
    }

    //初始化垂直跑马灯
    private void initTitleRollText()
    {
        MarqueeView mv = findViewById(R.id.news_title_marquee);

        List<String> textList = new ArrayList<>();
        textList.add("多低房贷利率破6% | 日本现巨大3D猫咪");
        textList.add("神州租车正式退市 | 最后一届90后毕业");
        textList.add("360借条APP被下架 | 陕西迎暴雨天气");
        textList.add("新版Model Y上市 | 季播剧云顶天宫定档");

        List<View> textViewList = new ArrayList<>();

        textViewList.clear();//记得加这句话，不然可能会产生重影现象
        for (int i = 0; i < textList.size(); i++)
        {
            //设置滚动的单个布局
            LinearLayout moreView = (LinearLayout) LayoutInflater.from(this)
                                                       .inflate(R.layout.news_title_search, null);
            //初始化布局的控件
            TextView tv1 = moreView.findViewById(R.id.news_title_search);

            //进行对控件赋值
            tv1.setText(textList.get(i));

            //添加到循环滚动数组里面去
            textViewList.add(moreView);
        }

        mv.setViews(textViewList);
    }

    private void replaceHomeFragment(int id)
    {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        for (int i = 0; i < mHomeFragments.size(); i++)
        {
            ft.hide(mHomeFragments.get(i));
            switch (id)
            {
                case R.id.news_main:
                    ft.show(mHomeFragments.get(0));
                    break;

                case R.id.news_video:
                    ft.show(mHomeFragments.get(1));
                    break;

                case R.id.news_cinema:
                    ft.show(mHomeFragments.get(2));
                    break;

                case R.id.news_mine:
                    ft.show(mHomeFragments.get(3));
                    break;
            }
        }

        ft.commit();
    }

    private void initData()
    {
//        weatherLogic.requestWeatherCityList();
    }

    @Override
    public void onCitylistReady(String cityId)
    {
        weatherLogic.requestCityWeather(cityId);
    }

    @Override
    public void onCityWeatherResult(CityWeather cityWeather)
    {
        Log.d(TAG, "城市名称：" + cityWeather.getCity());
    }

    @SuppressLint("JavascriptInterface")
    private void init()
    {
        String result = "";

        BridgeWebView webview = findViewById(R.id.web_view);
        webview.setDefaultHandler(new DefaultHandler());
        webview.setWebChromeClient(new WebChromeClient());
        webview.loadUrl("file:///android_asset/test.html");
//      注册监听方法当js中调用callHandler方法时会调用此方法（handlerName必须和js中相同）
        webview.registerHandler("submitFromWeb", new BridgeHandler()
        {
            @Override
            public void handler(String data, CallBackFunction function)
            {
                Log.e("TAG", "js返回：" + data);
                //显示js传递给Android的消息
                Toast.makeText(MainActivity.this, "js返回:" + data,
                    Toast.LENGTH_LONG).show();
                //Android返回给JS的消息
                function.onCallBack("我是js调用Android返回数据：" + result);
            }
        });

        //调用js中的方法（必须和js中的handlerName想同）
        webview.callHandler("functionInJs",
            "Android调用js66", new CallBackFunction()
            {
                @Override
                public void onCallBack(String data)
                {
                    Log.e("TAG", "onCallBack:" + data);
                    Toast.makeText(MainActivity.this, data,
                        Toast.LENGTH_LONG).show();
                }
            });
    }

    //JS中通过"别名"获取改对象，
    //并能够通过此对象调用被@JavascriptInterface标注的方法
    class JSConnection
    {

        @JavascriptInterface
        public void toast(String toast)
        {
            Toast.makeText(MainActivity.this,
                toast, Toast.LENGTH_SHORT).show();
        }
    }

}